const { mainThreadsSleep } = require("./utils/utils");
ui.layout(
  <frame>
    <webview id="webview" />
  </frame>
);

const webView = ui.webview;
const jsBridge = webView.jsBridge;

declare var __DevIp__: string;
if (typeof __DevIp__ === "string") {
  webView.loadUrl(`http://${__DevIp__}:5173/`);
} else {
  webView.loadLocalFile(files.path("./website"));
}

let w: any, execution: any;

const createRawWindow = (): void => {
  if (w) return
  if (!floaty.checkPermission()){
    floaty.requestPermission();
  }
  w = floaty.rawWindow(
    <frame bg='#40000000' w="*" h="*">
      <scroll id="scrollView" w="*" h="*">
        <vertical id="container">
          <text id="text" text="请勿操作屏幕" />
        </vertical>
      </scroll>
    </frame>
  );
  // w.setAdjustEnabled(false)
  w.setPosition(50, 200);
  w.setSize(550, 400)
  // w.exitOnClose();
}


const scriptStart = async (url:string, data: object|void) => {
  if(execution){
    addContent('已有脚本正在执行，请稍后')
  }
  let _path = __dirname + '/' + url.split('/')[0]
  console.log(_path);
  
  execution = engines.execScriptFile(url, { path: _path, delay : 1000})
  await mainThreadsSleep()
  let engine = execution.getEngine()
  console.log(data);
  engine.execArgv.data = data
  return engine
}

const addContent = (text: string, color: string = '#34d058'): void => {
  let textView = ui.inflate(<text textColor="#34d058" />, w.container)
  textView.setText(text)
  textView.setTextColor(colors.parseColor(color))
  w.container.addView(textView)
  w.scrollView.post(() => {
    w.scrollView.fullScroll(android.view.View.FOCUS_DOWN);
  });
}


jsBridge.registerHandler("start", (data: string) => {
  let res = JSON.parse(data)
  scriptStart(res.path, res)
  // scriptStart('./tiktok/operation-logic.js')
});


events.on("exit", () => {
  // 停止所有正在运行的脚本
  engines.stopAll();
  threads.shutDownAll();
});

events.broadcast.on("log", function(data:string) {
  console.log('log', data);
  data = JSON.parse(data)
  if (typeof data === 'object') {
    const {text, color} = data
    addContent(text, color)
  }else{
    addContent(data)
  }
});

createRawWindow()


threads.start(function() {
  try {
    console.log(addContent);
    
    addContent("音量下键监听已启动 - 按音量下键可退出程序");
    
    // 监听音量下键
    events.observeKey();
    events.onKeyDown("volume_down", function() {
        addContent("检测到音量下键，正在退出程序...");
        
        // 停止所有线程
        engines.stopAll();
        threads.shutDownAll();
        // 延迟一点时间后退出程序，以便toast消息能够显示
        setTimeout(function() {
            exit();
        }, 1000);
    });
  } catch (e) {
    console.error("音量键监听器错误: " + e);
  }
});


// 初始化内容
addContent("================");
addContent("     金币助手    ");
addContent("================");